package cn.kgc.novel.utils;

import cn.hutool.core.date.DateUtil;
import cn.kgc.novel.controller.UsersController;
import cn.kgc.novel.mapper.UsersMapper;
import cn.kgc.novel.pojo.Users;
import cn.kgc.novel.service.UsersService;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
@Component
public class JWTUtil {
    @Resource
    private UsersService usersService;

    public static String getToken(String id,String password){
        return JWT.create().withAudience(id)//设置以id为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2))//设置token超时时间
                .sign(Algorithm.HMAC256(password));//设置以密码作为密钥
    }
    //获取token中的载荷
    public static Map<String, Claim> getPayloadFromToken(String token, String password){
        Verification require = JWT.require(Algorithm.HMAC256(password));
        JWTVerifier build = require.build();
        DecodedJWT verify = build.verify(token);
        Map<String, Claim> claims = verify.getClaims();
        return claims;
    }

    //验证token
    public static DecodedJWT verify(String token,String password){
        return JWT.require(Algorithm.HMAC256(password)).build().verify(token);
    }

    //获取用户信息

    public Users getCurrentuser(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        String id = JWT.decode(token).getAudience().get(0);
        Users user = usersService.findById(Integer.parseInt(id));
        System.out.println(user);
        return user;
    }


}
